import unittest

from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol

from hbase import Hbase, ttypes


transport = TTransport.TBufferedTransport( TSocket.TSocket('localhost', 9090))
protocol = TBinaryProtocol.TBinaryProtocol(transport)


class ScannerTest(unittest.TestCase):

    client = Hbase.Client(protocol)
    test_table = 'test_table'
    n_mutations = 1000


    def cleanup(self):
        for t in self.client.getTableNames():
            if t == self.test_table:
                if self.client.isTableEnabled(t):
                    self.client.disableTable(t)
                self.client.deleteTable(t)


    def setUp(self):
        transport.open()
        self.cleanup()

        client = self.client
        test_table = self.test_table

        columns = [Hbase.ColumnDescriptor({'name': 'foo:'}),
                   Hbase.ColumnDescriptor({'name': 'bar:'})]
        client.createTable(test_table, columns)
        mutations = []
        for i in xrange(0, self.n_mutations):
            foo = str(i)
            bar = str(self.n_mutations - i)
            mutations.append(Hbase.BatchMutation({'row': 'row-%03d' % i,
                'mutations': [Hbase.Mutation({'column': 'foo:', 'value': foo}),
                              Hbase.Mutation({'column': 'bar:', 'value': bar})]}))
        client.mutateRows(test_table, mutations)


    def tearDown(self):
        transport.close()


    def test_scanner_open(self):
        client = self.client
        test_table = self.test_table
        n_mutations = self.n_mutations

        scanner = client.scannerOpen(test_table, '', ['no_such_column:'])
        client.scannerClose(scanner)

        self.assertRaises(ttypes.IOError, client.scannerOpen,
            test_table, '', ['foo'])

        scanner = client.scannerOpen(test_table, '', ['foo:'])
        client.scannerClose(scanner)

        scanner = client.scannerOpen(test_table, '', ['foo:', 'bar:'])
        client.scannerClose(scanner)

        self.assertRaises(ttypes.IOError, client.scannerOpen,
            test_table, '', ['foo:', 'bar'])


    def test_scanner_get(self):
        client = self.client
        test_table = self.test_table
        n_mutations = self.n_mutations

        scanner = client.scannerOpen(test_table, '', ['foo:'])
        for i in xrange(0, n_mutations):
            client.scannerGet(scanner)
        self.assertRaises(ttypes.NotFound, client.scannerGet, scanner)
        client.scannerClose(scanner)

        half = n_mutations / 2
        scanner = client.scannerOpen(test_table, 'row-%03d' % half, ['foo:'])
        for i in xrange(0, half):
            client.scannerGet(scanner)
        self.assertRaises(ttypes.NotFound, client.scannerGet, scanner)
        client.scannerClose(scanner)
